package com.xiaoxx.config;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.function.Supplier;

/**
 * @Author HX
 * @Date 2022/6/22 17:15
 */
@Component
public class ThreadUtils {
    private static ThreadPoolTaskExecutor executor;

    @Resource(name = "myThreadPool")
    public void setExecutor(ThreadPoolTaskExecutor executor) {
        ThreadUtils.executor = executor;
    }

    /**
     *异步执行方法
     * @param task
     */
    public static void asyncExecute(Runnable task) {
        ThreadUtils.executor.execute(task);

    }

    public static void  asyncSumbit(Runnable task){
        ThreadUtils.executor.submit(task);
    }

    public static <T> Future<T> asyncSumbit(Callable<T> task){
        Future<T> submit = ThreadUtils.executor.submit(task);
        return  submit;
    }

    public static <T> CompletableFuture<T> asyncCompletableFuture(Supplier<T> task){
        CompletableFuture<T> completableFuture = CompletableFuture.supplyAsync(task, executor);
        return  completableFuture;
    }
    public static  CompletableFuture<Void> asyncCompletableFuture(Runnable task){
     return CompletableFuture.runAsync(task, executor);
    }
}
